package com.ffyc.ssm.service;

import com.ffyc.ssm.dao.AdminDao;
import com.ffyc.ssm.modle.Admin;
import com.ffyc.ssm.modle.Role;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class AdminService {
    @Autowired
    AdminDao adminDao;

    @Transactional
    public List<Admin> listAdmin(Admin admin){
       return adminDao.getList();
    }
    @Transactional
    public List<Role> getroleslist() {
        return adminDao.getrolelist();
    }
    @Transactional
    public  void saveAdmin(Admin admin){
        //1、密码 默认值111 从电话中截取一部分 密码加密存储
        String password = DigestUtils.md2Hex("111");
        admin.setPassword(password);
        //2、存储管理员信息，返回返回管理员id
        adminDao.insertAdmin(admin);
        //3、存储管理员和角色关系
       if (admin.getRoleId()!=null){
           for (Integer roleid: admin.getRoleId()
                ) {
    adminDao.insertAdminRole(admin.getId(),roleid);
           }
       }

    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.md2Hex("111"));
        System.out.println(DigestUtils.md2Hex("444"));
        System.out.println(DigestUtils.md2Hex("333"));
    }

    @Transactional
    public Admin findAdmin(Integer id) {
        return adminDao.findAdmin(id);
    }
    //修改管理员表
/*    @Transactional
    public void alertAdmin(Admin admin) {
        //修改管理员表
        adminDao.alterAdmin(admin);
        //重写存储管理员和角色关系
        if (admin.getRoleId()!=null){
            for (Integer roleid:admin.getRoleId()
                 ) {
                adminDao.insertAdminRole(admin.getId(),roleid);
            }
        }
    }*/
    @Transactional
    public void delete(Integer id){
        adminDao.deleteAdminRole(id);
        adminDao.deleteAdmin(id);
    }

    public void updateAdmin(Admin a) {
        adminDao.updateAdmin(a);
    }

    public void update(Map<String, String> map) {
        adminDao.update(map);
    }


    public void upsaveAdmin(Admin admin) {
        //修改管理员表
        adminDao.upsaveAdmin(admin);
        //删除原来的管理员 角色 关系
        adminDao.deleteAdminRole(admin.getId());
        //重写存储管理员和角色关系
        if(admin.getRoleId()!=null){
            for (Integer roleid : admin.getRoleId()){
                adminDao.insertAdminRole(admin.getId(),roleid);
            }
        }
    }
}
